//
//  ZHPopupMenu.m
//  ZHPopupMenu
//
//  Created by Basic on 16/4/5.
//  Copyright © 2016年 zhihan. All rights reserved.
//

#import "ZHPopupMenu.h"
#import "ZHPopupMenuView.h"
#import <BCFoundation/BCFoundationUtils.h>
#import <BCUIKit/UIViewController+ZHPage.h>

#define kZHPopupMenu_AnimatedDuration               0.2
//#define kZHPopupMenu_CenterOffsetY                  0//menu center y 偏移
#define kZHPopupMenu_BgColor                        [UIColor clearColor]


@interface ZHPopupMenu () <UIGestureRecognizerDelegate>
@property (nonatomic, strong) UIView    *backgroundView;
@property (nonatomic, strong) ZHPopupMenuView   *popMenuView;
@property (nonatomic, assign) CGRect    senderFrame;
@property (nonatomic, strong) NSArray<ZHPopupMenuItemModel*>    *menuArray;
@property (nonatomic, assign) BOOL  isCurrentlyOnScreen;

@end

@implementation ZHPopupMenu
//MARK: - system
static ZHPopupMenu *kZHPopupMenuInstance;
+(instancetype )sharedMenu {
    @synchronized (self) {
        if(!kZHPopupMenuInstance){
            kZHPopupMenuInstance = [[[self class] alloc] init];
        }
    }
    return kZHPopupMenuInstance;
}
-(instancetype)init {
    self = [super init];
    if (self) {
        _menuBgColor = UIColor.blackColor;
        _menuTitleColor = UIColor.whiteColor;
        _menuTitleFont = [UIFont systemFontOfSize:14];
        _menuWidth = 130;
        _lineHeight = 44;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChangeStatusBarOrientationNotification:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    }
    return self;
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter]  removeObserver:self];
#ifdef DEBUG
    NSLog(@"ZHPopupMenu dealloc");
#endif
}

//MARK: - Public Method
+(BOOL)isShowing {
    return (kZHPopupMenuInstance!=nil);
}
-(void)showMenu:(NSArray<ZHPopupMenuItemModel *> *)menuArray {
    self.menuArray = menuArray;
    if (!self.senderView) {
        if (self.senderPoint.x == 0 && self.senderPoint.y == 0) {
            self.senderFrame = CGRectZero;
        } else {
            self.senderFrame = CGRectMake(self.senderPoint.x, self.senderPoint.y, self.menuWidth, self.lineHeight*self.menuArray.count);
        }
    }
    if ([NSThread isMainThread]) {
        [self.backgroundView addSubview:self.popMenuView];
        [self.containerView addSubview:self.backgroundView];
        [self adjustPopOverMenu];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.backgroundView addSubview:self.popMenuView];
            [self.containerView addSubview:self.backgroundView];
            [self adjustPopOverMenu];
        });
    }
}
+(void)dismiss {
    [kZHPopupMenuInstance hideMenu:-1 withMenuItem:nil];
}

//MARK: - 刷新弹层
-(void)adjustPopOverMenu {
    if (self.backgroundColor) {
        self.backgroundView.backgroundColor = self.backgroundColor;
    }
    [self.backgroundView setFrame:CGRectMake(0, 0, kBCSCREEN_WIDTH, kBCSCREEN_HEIGHT)];
    CGRect senderRect;
    if (self.senderView) {
        senderRect = [self.senderView.superview convertRect:self.senderView.frame toView:self.backgroundView];
    } else {
        senderRect = self.senderFrame;
    }
    if (senderRect.origin.y > kBCSCREEN_HEIGHT) {
        senderRect.origin.y = kBCSCREEN_HEIGHT;
    }
    CGFloat menuHeight = self.lineHeight * self.menuArray.count + kZHPopupMenuView_MenuArrowHeight;
    CGPoint menuArrowPoint = CGPointMake(senderRect.origin.x + (senderRect.size.width)/2, 0);
    CGFloat menuX = 0;
    CGRect menuRect = CGRectZero;
    BOOL shouldAutoScroll = NO;
    if (self.direction == ZHPopupMenuDirectionUnknow) {
        //未知方向，自动识别
        if (senderRect.origin.y + senderRect.size.height/2  < kBCSCREEN_HEIGHT/2) {
            self.direction = ZHPopupMenuDirectionUp;
        }
        else{
            self.direction = ZHPopupMenuDirectionDown;
        }
    }
    if (self.direction == ZHPopupMenuDirectionUp) {
        //箭头朝上
        menuArrowPoint.y = 0;
    }
    else{
        //箭头朝下
        menuArrowPoint.y = menuHeight;
    }
    if (menuArrowPoint.x + self.menuWidth/2 + kZHPopupMenuDefaultMargin-self.offsetX > kBCSCREEN_WIDTH) {
        //超过屏幕右侧
        menuArrowPoint.x = MIN(menuArrowPoint.x - (kBCSCREEN_WIDTH - self.menuWidth - kZHPopupMenuDefaultMargin+self.offsetX), self.menuWidth - kZHPopupMenuView_MenuArrowWidth - kZHPopupMenuDefaultMargin);
        menuX = kBCSCREEN_WIDTH - self.menuWidth - kZHPopupMenuDefaultMargin+self.offsetX;
    }
    else if (menuArrowPoint.x - self.menuWidth/2 - kZHPopupMenuDefaultMargin < 0){
        //超出屏幕左侧
        menuArrowPoint.x = MAX( kZHPopupMenuView_MenuRadius + kZHPopupMenuView_MenuArrowWidth, menuArrowPoint.x - kZHPopupMenuDefaultMargin);
        menuX = kZHPopupMenuDefaultMargin+self.offsetX;
    }
    else{
        menuArrowPoint.x = self.menuWidth/2.0;
        menuX = senderRect.origin.x + (senderRect.size.width)/2 - self.menuWidth/2+self.offsetX;
    }
    //调整内容view的frame
    if (self.direction == ZHPopupMenuDirectionUp) {
        CGFloat kMenuTop = senderRect.origin.y + menuRect.size.height+self.offsetY;
        menuRect = CGRectMake(menuX, kMenuTop, self.menuWidth, menuHeight);
        if (kMenuTop > kBCSCREEN_HEIGHT) {
            menuRect.size.height = kBCSCREEN_HEIGHT - self.offsetY - menuRect.origin.y - kZHPopupMenuDefaultMargin;
            shouldAutoScroll = YES;
        }
    }
    else{
        CGFloat kMenuTop = senderRect.origin.y - menuHeight-self.offsetY;
        menuRect = CGRectMake(menuX, kMenuTop, self.menuWidth, menuHeight);
        if (kMenuTop  < 0) {
            menuRect = CGRectMake(menuX, kZHPopupMenuDefaultMargin, self.menuWidth, senderRect.origin.y - kZHPopupMenuDefaultMargin);
            menuArrowPoint.y = senderRect.origin.y;
            shouldAutoScroll = YES;
        }
    }
    menuArrowPoint.x += self.arrowOffsetX;
    [self prepareToShowWithMenuRect:menuRect menuArrowPoint:menuArrowPoint shouldAutoScroll:shouldAutoScroll];
    [self showMenu];
}
-(void)prepareToShowWithMenuRect:(CGRect)menuRect menuArrowPoint:(CGPoint)menuArrowPoint shouldAutoScroll:(BOOL)shouldAutoScroll {
    CGPoint anchorPoint = CGPointMake(menuArrowPoint.x/menuRect.size.width, 0);
    if (self.direction == ZHPopupMenuDirectionDown) {
        anchorPoint = CGPointMake(menuArrowPoint.x/menuRect.size.width, 1);
    }
    self.popMenuView.anglePoint = menuArrowPoint;
    self.popMenuView.shouldAutoScroll = shouldAutoScroll;
    self.popMenuView.arrowDirection = self.direction;
//    self.popMenuView.transform = CGAffineTransformMakeScale(1, 1);
    @BCWeakify(self);
    [self.popMenuView showWithFrame:menuRect withNameArray:self.menuArray doneBlock:^(NSInteger selectedIndex, ZHPopupMenuItemModel *menu) {
        @BCStrongify(self);
        [self hideMenu:selectedIndex withMenuItem:menu];
    }];
    [self setAnchorPoint:anchorPoint forView:_popMenuView];
//    self.popMenuView.transform = CGAffineTransformMakeScale(0.1, 0.1);
}
-(void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view {
    CGPoint newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x,
                                   view.bounds.size.height * anchorPoint.y);
    CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x,
                                   view.bounds.size.height * view.layer.anchorPoint.y);
    newPoint = CGPointApplyAffineTransform(newPoint, view.transform);
    oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform);
    CGPoint position = view.layer.position;
    position.x -= oldPoint.x;
    position.x += newPoint.x;
    position.y -= oldPoint.y;
    position.y += newPoint.y;
    view.layer.position = position;
    view.layer.anchorPoint = anchorPoint;
}


//MARK: - UIGestureRecognizerDelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
//    CGPoint point = [touch locationInView:_popMenuView];
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}


//MARK: - Event
-(void)onBackgroundViewTapped:(UIGestureRecognizer *)gesture {
    [self hideMenu:-1 withMenuItem:nil];
}

//MARK: - 显示 隐藏 menu
- (void)showMenu {
    self.isCurrentlyOnScreen = YES;
    [UIView animateWithDuration:kZHPopupMenu_AnimatedDuration animations:^{
         self.popMenuView.alpha = 1;
     }];
}
- (void)hideMenu:(NSInteger )menuTag withMenuItem:(ZHPopupMenuItemModel *)menuItem {
    self.isCurrentlyOnScreen = NO;
    [UIView animateWithDuration:kZHPopupMenu_AnimatedDuration animations:^{
        self.popMenuView.alpha = 0;
        //         _popMenuView.transform = CGAffineTransformMakeScale(0.1, 0.1);
    } completion:^(BOOL finished) {
        if (finished) {
            [self.popMenuView removeFromSuperview];
            [self.backgroundView removeFromSuperview];
            if (!menuItem) {
                //取消
                if ([self.delegate respondsToSelector:@selector(zhPopupMenuDismiss:)]) {
                    [self.delegate zhPopupMenuDismiss:self];
                }
            }
            else{
                //选择item
                if ([self.delegate respondsToSelector:@selector(zhPopupMenu:didSelectedItem:selectedItem:)]) {
                    [self.delegate zhPopupMenu:self didSelectedItem:menuTag selectedItem:menuItem];
                }
            }
            //销毁自己
            kZHPopupMenuInstance = nil;
        }
    }];
}

//MARK: - notifcation
-(void)onChangeStatusBarOrientationNotification:(NSNotification *)notification {
    if (self.isCurrentlyOnScreen) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self adjustPopOverMenu];
        });
    }
}

//MARK: - getter
-(UIView *)backgroundView {
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onBackgroundViewTapped:)];
        tap.delegate = self;
        [_backgroundView addGestureRecognizer:tap];
        _backgroundView.backgroundColor = kZHPopupMenu_BgColor;
    }
    return _backgroundView;
}
-(UIView *)containerView {
    if (!_containerView) {
        UIViewController *topVC = [UIViewController bc_topPage];
        _containerView = topVC.view;
    }
    return _containerView;
}
-(ZHPopupMenuView *)popMenuView {
    if (!_popMenuView) {
        _popMenuView = [[ZHPopupMenuView alloc] initWithFrame:CGRectZero];
        _popMenuView.menuBgColor = self.menuBgColor;
        _popMenuView.menuTitleColor = self.menuTitleColor;
        _popMenuView.menuShadowColor = self.menuShadowColor;
        _popMenuView.menuTitleFont = self.menuTitleFont;
        _popMenuView.alpha = 0;
        _popMenuView.hideArrow = self.hideArrow;
        _popMenuView.lineHeight = self.lineHeight;
    }
    return _popMenuView;
}
-(UIView *)contentView {
    return self.popMenuView;
}

@end
